package com.laoyang.rabbit;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.slf4j.spi.MDCAdapter;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Date;

/**
 * @author com.yyy
 * @Date 2020-09-12 11:59
 * @Email yangyouyuhd@163.com
 */
public class json转换 {


    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        User1 user1 = new User1("张三",18,new Date());
        String string = JSON.toJSONString(user1);
        User2<User1> user2 = JSON.parseObject(string,new TypeReference<User2<User1>>(){});
        System.out.println(user2);
        Field[] fields = user2.getClass().getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field.getType());
        }

        // 获取指定字段、并将json消息赋值给、
        Field data = user2.getClass().getDeclaredField("data");
        data.setAccessible(true);
        data.set(user2,JSON.parseObject(string));



        Class aClass = GenericsUtils.getSuperClassGenricType(user2.getClass());
        data.set(user2,JSON.parseObject(string,aClass));

    }

    @Data
    @ToString
    @NoArgsConstructor
    @AllArgsConstructor
    static class User1{
        private String name;
        private Integer age;
        private Date birthday;
    }

    @Data
    @ToString
    @NoArgsConstructor
    @AllArgsConstructor
    static class User2<T>{
//        T data;
        private String name;
        private Integer age;
        private Date birthday;

    }


    static class GenericsUtils {
        /**
         * 通过反射,获得定义Class时声明的父类的范型参数的类型
         *
         * @param clazz
         * @return 返回第一个类型
         */
        public static Class getSuperClassGenricType(Class clazz) {
            return getSuperClassGenricType(clazz, 0);
        }

        public static Class getSuperClassGenricType(Class clazz, int index)
                throws IndexOutOfBoundsException {
            Type genType = clazz.getGenericSuperclass();
            if (!(genType instanceof ParameterizedType)) {
                return Object.class;
            }
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            if (index >= params.length || index < 0) {
                return Object.class;
            }
            if (!(params[index] instanceof Class)) {
                return Object.class;
            }
            return (Class) params[index];
        }
    }



}
